package com.admin.common.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;

import com.admin.domain.AdminDO;

/**
 * 
 * @author ZY
 * @date 2018/10/18
 */
public class ShiroUtils {

    public static Subject getSubjct() {
        return SecurityUtils.getSubject();
    }

    public static AdminDO getUser() {
        Object object = getSubjct().getPrincipal();
        return (AdminDO)object;
    }

    public static Integer getUserId() {
        return getUser().getUserId();
    }

    public static void logout() {
        clearCachedAuthorization();
        getSubjct().logout();
    }

    public static String getUserName() {
        return getUser().getUsername();
    }

    public static String getMemberLevel() {
        return getUser().getMemberLevel();
    }

    public static String getRealname() {
        return getUser().getRealname();
    }

    public static String getMobile() {
        return getUser().getMobile();
    }

    /**
     * 清空所有人权限缓存
     * 
     */
    public static void clearAllCachedAuthorization() {
        RealmSecurityManager rsm = (RealmSecurityManager)SecurityUtils.getSecurityManager();
        UserRealm realm = (UserRealm)rsm.getRealms().iterator().next();
        realm.clearAllCachedAuthorization();;
    }

    /**
     * 清除用户权限缓存、登录缓存（当前登录操作人）
     * 
     * 
     */
    public static void clearCachedAuthorization() {
        clearCachedAuthorization(ShiroUtils.getUserName());
    }

    /**
     * 清除指定用户权限缓存、登录缓存（指定用户）
     * 
     * @param username
     */
    public static void clearCachedAuthorization(String username) {
        RealmSecurityManager rsm = (RealmSecurityManager)SecurityUtils.getSecurityManager();
        UserRealm realm = (UserRealm)rsm.getRealms().iterator().next();
        realm.clearCachedAuthorization(username);
    }
}
